package com.billdowney.service.impl.user;

import java.util.List;
import java.util.Optional;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import com.billdowney.dao.user.UserInfoDao;
import com.billdowney.dao.user.UserLoginInfoDao;
import com.billdowney.entity.user.UserInfo;
import com.billdowney.entity.user.UserLoginInfo;
import com.billdowney.exception.BizException;
import com.billdowney.service.impl.base.BaseServiceImpl;
import com.billdowney.service.interfaces.user.UserInfoValidateService;
import com.billdowney.util.CommonUtil;

/**
 * @ClassName: UserInfoValidateServiceImpl
 * @Description: 用户接口验证实现
 * @author 超级小富翁 - BillDowney
 * @date 2018年2月2日 下午4:31:30
 */
@Service
public class UserInfoValidateServiceImpl extends BaseServiceImpl<UserInfoDao, UserInfo, String>
		implements UserInfoValidateService {

	@Autowired
	private UserLoginInfoDao userLoginInfoDao;

	@Resource(type = UserInfoDao.class)
	@Override
	public void setDao(UserInfoDao dao) {
		super.dao = dao;
	}

	@Override
	public boolean validateUserLoginInfoRepeatField(UserLoginInfo userLoginInfo) throws Exception {
		List<UserLoginInfo> list = userLoginInfoDao.findList(userLoginInfo.getPhone(), userLoginInfo.getEmail(),
				userLoginInfo.getUsername());
		if (CommonUtil.isEmpty(list)) {
			return true;
		}
		UserLoginInfo old = list.get(0);
		if (CommonUtil.isNotEmpty(userLoginInfo.getId()) && userLoginInfo.getId().equals(old.getId())) {
			return true;
		}
		if (CommonUtil.isNotEmpty(old.getPhone()) && old.getPhone().equals(userLoginInfo.getPhone())) {
			throw new BizException(10210);
		} else if (CommonUtil.isNotEmpty(old.getUsername()) && old.getUsername().equals(userLoginInfo.getUsername())) {
			throw new BizException(10211);
		} else if (CommonUtil.isNotEmpty(old.getEmail()) && old.getEmail().equals(userLoginInfo.getEmail())) {
			throw new BizException(10212);
		}
		return true;
	}

	@Override
	public boolean validateUserBasicInfoRepeatField(UserInfo userBasicInfo) throws Exception {
		UserInfo query = new UserInfo();
		query.setNickname(userBasicInfo.getNickname());
		Optional<UserInfo> data = dao.findOne(Example.of(query));
		if (data.isPresent()) {
			UserInfo old = data.get();
			if (CommonUtil.isNotEmpty(userBasicInfo.getId()) && userBasicInfo.getId().equals(old.getId())) {
				return true;
			} else if (CommonUtil.isNotEmpty(userBasicInfo.getNickname())
					&& userBasicInfo.getNickname().equals(old.getNickname())) {
				throw new BizException(10213);
			}
		}
		return true;
	}
}
